<template>
  <div class="course-img">
    <el-form-item :label="label">
      <!-- 进度组件 -->
      <el-progress type="circle" :percentage="percentage"
      :width="178" v-if="isUploading"
      :status="percentage === 100 ? 'success' : 'undefined'"></el-progress>
      <!-- 上传组件 -->
      <el-upload
        v-else
        class="avatar-uploader"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :http-request="handleUpload">
        <!-- img是预览图片的显示位置 -->
        <img v-if="value" :src="value" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
  </div>
</template>
<script>
import { uploadCourseImg } from '@/services/course'
export default {
  name: 'CourseImg',
  data () {
    return {
      // 保存上传状态
      isUploading: false,
      // 用于保存上传进度百分比
      percentage: 0
    }
  },
  props: {
    value: {
      type: String
    },
    label: {
      type: String
    },
    limit: {
      type: Number,
      default: 2
    }
  },
  methods: {
    // 进度展示
    // 上传图片成功时的操作
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传前的操作
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < this.limit
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 图片上传处理函数 option为上传的相关信息
    async handleUpload (option) {
    // 开始上传图片将上传状态设置为正在上传
      this.isUploading = true
      //   console.log(option)
      // option.file是要上传图片文件的 的信息
      // 使用FormData处理
      const fd = new FormData()
      fd.append('file', option.file)
      // 发送上传请求
      // console.log(fd)
      const { data } = await uploadCourseImg(fd, thing => {
        this.percentage = Math.floor(thing.loaded / thing.total * 100)
      })
      // console.log(data)
      if (data.code === '000000') {
        // data.data.name 是服务端相应的是图片上传后的线上地址
        this.$emit('input', data.data.name)
        // 上传完毕将上传状态设置为关闭上传
        this.isUploading = false
        // 上传完毕将上传进度改为0 避免再次上传时上次的图出现回退
        this.percentage = 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
